/* 
收集用户点击页面的坐标的hook函数
*/
import {
  ref,
  onMounted,
  onBeforeUnmount
} from "vue"

export default function useClickPosition() {
  const x = ref(0)
  const y = ref(0)

  const updatePosition = (e: MouseEvent) => {
    console.log('click...')
    const {pageX, pageY} = e
    x.value = pageX
    y.value = pageY
  }

  // 在组件挂载后, 给整个页面绑定监听
  onMounted(() => {
    document.addEventListener('click', updatePosition)
  })

  // 在组件卸载前, 解绑监听
  onBeforeUnmount(() => {
    document.removeEventListener('click', updatePosition)
  })
  
  return {
    x,
    y
  }
}